package com.weijun.keepalive_daemon.service

import android.app.job.JobParameters
import android.app.job.JobService
import android.content.Context
import android.content.Intent
import android.os.Build
import android.os.Bundle
import android.os.Parcelable
import com.weijun.keepalive_daemon.logE
import com.weijun.keepalive_daemon.utils.IntentUtils

/**
 * @author: weijun
 * date: 2023/7/10
 * description:
 */
class IntentJobService :JobService() {

    companion object {
        const val IS_ACTIVITY = "is_activity"
        const val JOB_ID = 1001
    }

    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        "IntentJobService onStartCommand".logE()
        return START_STICKY
    }

    override fun onStartJob(params: JobParameters?): Boolean {
        if (Build.VERSION.SDK_INT >= 28) {
            val transientExtras = params?.transientExtras
            val intent = transientExtras?.getParcelable<Parcelable>("android.intent.extra.INTENT") as Intent?
            if (intent != null) {
                if (transientExtras?.getBoolean(IS_ACTIVITY) == true) {
                    IntentUtils.startActivitySafe(this as Context, intent, false)
                } else {
                    try {
                        startService(intent)
                    } catch (ignore: Exception) { }
                }
            }
        }
        return false
    }

    override fun onStopJob(params: JobParameters?): Boolean {
        return false
    }
}